<?php

namespace app\modules\Product\controllers;

use Yii;
use app\modules\Product\models\Product;
use app\modules\Product\models\Word;
use app\modules\Product\models\ProductSearch;
use app\modules\Product\models\ProductRoom;
use app\modules\Product\models\ProductRoomPrice;
use app\modules\Product\models\Template;
use app\modules\Product\models\Excel;
use app\modules\Order\models\Order;
use dektrium\user\models\User;
use app\modules\Order\models\OrderCustomer;
use yii\web\UploadedFile;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use yii\imagine\Image;
use app\modules\Cruise\models\Room;
use app\modules\Cruise\models\Cruise;

/**
 * ProductController implements the CRUD actions for Product model.
 */
class ProductController extends Controller
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
		return [
			'verbs' => [
				'class' => VerbFilter::className(),
				'actions' => [
					'delete' => ['post'],
				],
			],
			'access' => [
				'class' => AccessControl::className(),
				'rules' => [
					[
						'allow' => true, 
						'actions' => ['index','create','view','update','delete', 'clone', 'trip', 'save', 'sort', 'word','file-upload','del-img','order-excel','lines', 'copy','neword','datelimit','product-price','download-excel'], 
						'roles' => ['@'],
						//'matchCallback' => function ($rule, $action) {
						//	return  (Yii::$app->user->identity->username == 'admin') ? true : false;
						//}
					],
                    [
                        'allow' => true,
                        'actions' => ['neword','word','file-upload','del-img'],
                        'roles' => ['?'],
                    ],
				],
			],
		];
    }


    // 模板添加航线
    public function actionClone($template_id){//{{{
        if(!is_numeric($template_id)){
            return false;
        }
    
        $template = Template::findOne($template_id);

        if($template ){
            $model = new Product();
            $model->name = $template->name;
            $model->cruise_id = $template->cruise_id;
            $model->from_city = $template->from_city;
            $model->to_city = $template->to_city;
            $model->line = $template->line;
            $model->cost = $template->cost;
            $model->nocost = $template->nocost;
            $model->cancel= $template->cancel;
            $model->discount = $template->discount;
            $model->visa = $template->visa;
            $model->trip = $template->trip;
            $model->type= $template->type;
            $model->signup = $template->signup;
            $model->land = $template->land;
            $model->expense = $template->expense;
            $model->go_city = $template->go_city;
            $model->return_city = $template->return_city;
            $model->special = $template->special;
            $model->important = $template->important;
            $model->safe_1 = $template->safe_1;
            $model->safe_2 = $template->safe_2;
            $model->safe_3 = $template->safe_3;

            $ret = $model->save();
            
            return $this->redirect(['update', 'id' => $model->id]);
        }
    }//}}}


    /**
     * Lists all Product models.
     * @return mixed
     */
    public function actionIndex()
    {

		if(Yii::$app->user->can('product_index') ){
        	$searchModel = new ProductSearch();
        	$dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        	return $this->render('index', [
        	    'searchModel' => $searchModel,
        	    'dataProvider' => $dataProvider,
        	]);
		}
    }

    /**
     * Displays a single Product model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new Product model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new Product();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            $model->status = 1;
            $model->stock = 2;
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Updates an existing Product model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);
        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }

	// 设置占位有效期
	public function actionDatelimit($id, $date_limit=0){
        
        $model = $this->findModel($id);
        $old_date = $model->date_limit;
		$model->date_limit = $date_limit;

		if($model->save()){

            //占位日期变更通知用户
            if($old_date != $date_limit){
                //获取所有的用户;
                $users = User::find()->all();
                if($users){
                    //选择模板
                    $template_id = "2DJiYcN-Nq-HQk925MPwz5TmwUEKCKzAxCHXvqdxZVo";
                    $topcolor = '#FF0000';
                    foreach($users as $user){
                        if($user->profile->openId){
                            $data = [
                                'first'=>['value'=>"占位时间变更期通知",'color'=>"#A664A6"],
                                'OrderID'=>['value'=>'','color'=>'#000000'],
                                'PkgName'=>['value'=>$model->name,'color'=>'#000000'],
                                'TakeOffDate'=>['value'=>$model->go_time,'color'=>'#000000'],
                                'remark'=>[
                                    'value'=>sprintf("占位时间由%d天变更为%d天！",$old_date,$date_limit),
                                    'color'=>'#A664A6'
                                ],
                            ];
                            $template = [
                                'touser' => $user->profile->openId,
                                'template_id' => $template_id,
                                'url' => '',
                                'topcolor' => $topcolor,
                                'data' => $data
                            ];
                            $msg = yii::$app->notice->send($template);
                        }
                    }
                } 
            }

			print_r(json_encode(['output'=>$model->date_limit, 'message'=>"" ]));	
		}else{
			print_r(json_encode(['output'=>$model->date_limit, 'message'=>"save error" ]));	
		}

	}

    public function actionTrip($id){//{{{
        $model = $this->findModel($id);

        $ret = $this->tripdata($model); 
        return $this->render('_trip', ['model' => $model, 'example'=>$ret['example'], 'data'=>$ret['data']]);
    }//}}}

    public function actionSave(){//{{{
        
        $params = Yii::$app->request->post();

        $model = $this->findModel($params['id']);
        if ($model) {
            $model->trip = json_encode($params['Product']['trip']);
            $r = $model->save();
            $ret = $this->tripdata($model); 
            return $this->render('_trip', ['model' => $model, 'example'=>$ret['example'], 'data'=>$ret['data']]);
        }
    }//}}}



    private function tripdata($model){//{{{
        $day = $model->day;
        $arr = json_decode($model->trip, true);

        $data = $example = [];
        
        $dates = Yii::$app->dates->prDates($model->go_time, $model->return_time);
        
        if($arr){
            $cou = count($arr);
            if($cou < $day){ // 补充模板差的天数
               for($i=0;$i<$day-$cou; $i++){
                    $ex = ['title'=>'','eat'=>'','room'=>'','traffic'=>'','country'=>'', 'desc'=>'', 'time1'=>'', 'time2'=>'', 'type'=>'','visit'=>[['name'=>'','price'=>'','content'=>'']]];
                    $arr += [$cou+$i=>$ex]; 
               }
            }
        
            foreach($arr as $key=>$val){
                $data[$key] = $val;
                $example[$key]['content'] = sprintf("第%s项", $key+1);
            }
           
            if($model->trip_sort){
                $sort = explode(",", $model->trip_sort);

                $data = $this->compare($data, $sort);
                $example = $this->compare($example, $sort);
            }
        }
        return ['data'=>$data, 'example'=>$example];
    }//}}}


    public function compare($arr, $sort)
    {    
        $data = [];

        foreach($sort as $key=>$val){
            $data[$val] = $arr[$val] + ['key'=>$val];
        }

        return $data;
    }


    // 行程排序
    public function actionSort($id){//{{{
        $model = $this->findModel($id);
        
        $sort = Yii::$app->request->get('sort');
        if ($model) {
            $model->trip_sort = $sort;
            $r = $model->save();
            $ret = $this->tripdata($model); 
            return $this->render('_trip', ['model' => $model, 'example'=>$ret['example'], 'data'=>$ret['data']]);
        }
    }//}}}



    //行程图片上传
    public function actionFileUpload(){//{{{

        $model = new Product();

        $upload = UploadedFile::getInstance($model, "trip_img");

        $dir = sprintf("uploads/trip/%s",date("Ym"));

        if(!is_readable($dir)) {
            is_file($dir) or mkdir($dir,0755);
        }

        $suffix = $upload->extension;

        $path = sprintf('%s/%s.%s', $dir, uniqid(true), $suffix);

        $ret = $upload->saveAs($path);

        if($ret){
           
            $file_path = sprintf("%s/web/%s",yii::$app->basePath, $path);;
            $file_name = $path;
            $re = yii::$app->qiniu->uploadQiniu($file_path, $file_name);

            $params = Yii::$app->request->get();
            $product = Product::findOne($params['id']);
            if(!empty($product->trip_img)){
                $trip_img = json_decode($product->trip_img,true);
                $trip_img[$params['key']][] = $path;
            }else{
                $trip_img = [$params['key']=>[$path]];
            }
            
            $product->trip_img = json_encode($trip_img);
            $product->save();
        }
        print_r(json_encode($path));
    }//}}}

    //删除行程图片
    public function actionDelImg(){//{{{

        $params = Yii::$app->request->get();
        $product = Product::findOne($params['id']);
        if(!empty($product->trip_img)){
            $trip_img = json_decode($product->trip_img,true);
            foreach($trip_img as $key=>&$val){
                if($key == $params['key']){
                    if(isset($val) && !empty($val)){
                        unset($val[$params['img_id']]);
                    }   
                }
            }
            $product->trip_img = json_encode($trip_img);
            $product->save();
            print_r(true);
        }
        

    }//}}}

    //下载游轮价格
    public function actionProductPrice(){

        $model = new Product();

        return $this->render('product-price',['model'=>$model]);

    }

    private function replaceSpecialChar($strParam){
        $regex = "/\/|\~|\!|\@|\#|\\$|\%|\^|\&|\*|\(|\)|\_|\+|\{|\}|\:|\<|\>|\?|\[|\]|\,|\.|\/|\;|\'|\`|\-|\=|\\\|\|/";
        return preg_replace($regex,"",$strParam);
    }

    //下载游轮价格
    public function actionDownloadExcel(){
        $params = Yii::$app->request->get();
        $cruise_id = $params['Product']['cruise_id'];
        $start_time = $params['Product']['go_time'];
        $end_time = $params['Product']['return_time'];
        $type = $params['type'];

        if(!$cruise_id || !$start_time || !$end_time){
            return '缺少参数';
        }
        $cruise = Cruise::findOne($cruise_id);
        $product = Product::find()->where(['cruise_id'=>$cruise_id,'status'=>1])->andWhere(['>=','go_time',$start_time])->andWhere(['<=','go_time',$end_time])->orderBy('go_time')->all();
        if(!$product){
            return '没有团期!';
        }
        $objPHPExcel = new \PHPExcel();
        //获取所有房间
        $all_room = Room::find()->where(['cruise_id'=>$cruise_id,'status'=>1])->all();

        if ($type == 2){
            $data_arr = ['年份','月份','日期','成人价格','成人同业价格','成人库存','儿童价格','儿童库存','单房差价格'];
        }else{
            $data_arr = ['年份','月份','日期','成人价格','成人库存','儿童价格','儿童库存','单房差价格'];
        }

        $styleArray = array(  
            'borders' => array(  
                'allborders' => array(  
                    'style' => \PHPExcel_Style_Border::BORDER_THIN,//细边框   
                    'color' => array('argb' => '000000'),  
                ),  
            ),  
        );
        if($all_room){
            $key = 0;
            foreach($all_room as $room){

                $range = range($room->min, $room->num);
                foreach($range as $val){
                   
                    $sheet = $objPHPExcel->createSheet($key);
                    $title = sprintf('%s%s-%d人间',$room->name,$room->code,$val);
                    $sheet->setTitle($this->replaceSpecialChar($title));
                    $sheet->getDefaultStyle()->getFont()->setSize(9)->setName('微软雅黑');
                    $sheet->getDefaultStyle()->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER)->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);

                    $start = 2;
                    $sheet->fromArray($data_arr, NULL, 'A2');
                    foreach($product as $p){
                        $x = ProductRoom::find()->where(['product_id'=>$p->id,'room_id'=>$room->id,'people'=>$val])->andWhere(['>','price',0])->one();
                        $stock_num = $price = $inside_price ='';
                        if($x){
                            $price = $x->price;
                            $inside_price = $x->inside_price;
                            $stock_num = $x->num - $x->stockNum;

                        }

                        if ($type == 2){
                            $sheet->setCellValue(sprintf("A%d",$start+1),date('Y',strtotime($p->go_time)));

                            $sheet->setCellValue(sprintf("B%d",$start+1),date('n',strtotime($p->go_time)));

                            $sheet->setCellValue(sprintf("C%d",$start+1),date('j',strtotime($p->go_time)));

                            $sheet->setCellValue(sprintf("D%d",$start+1),$price);
                            $sheet->setCellValue(sprintf("E%d",$start+1),$inside_price);

                            $sheet->setCellValue(sprintf("F%d",$start+1),$stock_num);
                            $sheet->setCellValue(sprintf("G%d",$start+1),$price);
                            $sheet->setCellValue(sprintf("H%d",$start+1),$stock_num);
                            $sheet->setCellValue(sprintf("I%d",$start+1),$price);

                        }else{
                            $sheet->setCellValue(sprintf("A%d",$start+1),date('Y',strtotime($p->go_time)));

                            $sheet->setCellValue(sprintf("B%d",$start+1),date('n',strtotime($p->go_time)));

                            $sheet->setCellValue(sprintf("C%d",$start+1),date('j',strtotime($p->go_time)));

                            $sheet->setCellValue(sprintf("D%d",$start+1),$price);
                            $sheet->setCellValue(sprintf("E%d",$start+1),$stock_num);
                            $sheet->setCellValue(sprintf("F%d",$start+1),$price);
                            $sheet->setCellValue(sprintf("G%d",$start+1),$stock_num);
                            $sheet->setCellValue(sprintf("H%d",$start+1),$price);
                        }

                        $start++;

                    }
                    if ($type == 2){
                        $sheet->getStyle(sprintf("A2:I%d",$start))->applyFromArray($styleArray);
                    }
                    $sheet->getStyle(sprintf("A2:H%d",$start))->applyFromArray($styleArray);
                    $key++;   
                }

            }
        }else{
            return '没有房间信息';
        }

        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
        $fileName = sprintf("%s.xlsx",uniqid());
        $path = 'uploads/excel/'.date('Ym').'/';
        if(!is_dir($path)){  
              mkdir($path,0777,true);  
        }
        $file = $path.$fileName;
        $objWriter->save($file);
        
        $file_name = sprintf("%s-舱房价格表.xlsx",$cruise->name);

        header("Content-type: application/octet-stream");    
        header("Accept-Ranges: bytes");    
        header("Accept-Length: " . filesize($file));    
        header("Content-Disposition: attachment; filename=" .$file_name);    
        @readfile($file);
        exit();
        
    }

    /**
     * Deletes an existing Product model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the Product model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Product the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Product::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }

    /**
     *
     * 航线生成 WORD 文档
     *
     */
    public function actionWord($id,$type=1){
        $this->layout = false;

        $model = $this->findModel($id); 

        if(empty($model->go_time) || empty($model->return_time)){
            echo "行程信息不完整";
            return false; 
        }

        if($model->type == 1 || $model->type == 3){
            return  $this->render('word',['model'=>$model,'type'=>$type]);
        }else{
            return  $this->render('word2',['model'=>$model,'type'=>$type]);
        }

        // $word = new Word();
        // $file = $word->line($model);
    }

    /*
     * 新版WORD文档
     * 
     */
    public function actionNeword($id,$type=1){
        $this->layout = false;
        $model = $this->findModel($id); 

        if(empty($model->go_time) || empty($model->return_time)){
            echo "行程信息不完整";
            return false; 
        }
        return  $this->render('neword',['model'=>$model,'type'=>$type]);
    }



    /**
     *
     * 航线订单生成Excel文件 
     *
     */
    public function actionOrderExcel($id){
        $model = $this->findModel($id); 
        $excel = new Excel();
        $file = $excel->order($model);
        $filename = sprintf("%s.xlsx",$model->name);
        if(file_exists($file)){
            header('Content-Type: application/vnd.ms-excel');
            header('Content-Disposition: attachment;filename="'.$filename.'"');
            header('Cache-Control: max-age=0');
            header('Cache-Control: max-age=1');
            header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
            header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
            header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
            header('Pragma: public'); // HTTP/1.0
            readfile($file);
            exit();
        }    
    }



    /**
     * copy product model.
     * @return mixed
     */
    public function actionCopy($id)
    {
        if(empty($id)){
            throw new NotFoundHttpException('copy product The params id not exist.');
        }
        
        // 复制基础信息
        $model = $this->findModel($id);
        $_model = new  Product();
        $_model->cruise_id = $model->cruise_id;
        $_model->day = $model->day;
        $_model->from_city = $model->from_city;
        $_model->to_city = $model->to_city;
        $_model->name = $model->name;
        $_model->line = $model->line;
        $_model->cost = $model->cost;
        $_model->visa = $model->visa;
        $_model->trip = $model->trip;
        $_model->trip_sort = $model->trip_sort;
        $_model->nocost = $model->nocost;
        $_model->cancel = $model->cancel;
        $_model->discount = $model->discount;
        $_model->signup = $model->signup;
        $_model->land = $model->land;
        $_model->expense = $model->expense;
        $_model->type = $model->type;
        $_model->room_remark = $model->room_remark;
        $_model->rooms = $model->rooms;
        $_model->sale = $model->sale;
        $_model->go_city = $model->go_city;
        $_model->return_city = $model->return_city;
        $_model->special = $model->special;
        $_model->important = $model->important;
        $_model->safe_1 = $model->safe_1;
        $_model->safe_2 = $model->safe_2;
        $_model->safe_3 = $model->safe_3;
    
        if($_model->save()) {
            // 复制价格信息
            $room = ProductRoom::find()->where(['product_id'=>$id])->all();
            if($room){
                foreach($room as $m){

                    $_room = new ProductRoom();

                    $_room->product_id = $_model->id;
                    $_room->room_id = $m->room_id;
                    $_room->show = $m->show;
                    $_room->num  = $m->num;
                    $_room->sort = $m->sort;

                    $_room->people = $m->people;
                    $_room->price = $m->price;
                    $_room->inside_price = $m->inside_price;

                    $_room->save();

                    //$roomprice = ProductRoomPrice::find()->where(['product_room_id'=>$m->id])->all();
                    //if($roomprice){
                    //    foreach($roomprice as $p){
                    //       $_roomprice = new ProductRoomPrice();
                    //       $_roomprice->product_room_id = $_room->id;
                    //       $_roomprice->people = $p->people;
                    //       $_roomprice->price = $p->price;
                    //       $_roomprice->inside_price = $p->inside_price;
                    //       $_roomprice->show = $p->show;
                    //       $_roomprice->save();
                    //    }
                    //}
                }//foreach
            }//if
        }

        return $this->redirect(['update', 'id' => $_model->id]);
    }

}
